package com.payment.impl;

import java.math.BigDecimal;
import java.util.List;

import com.basic.service.contract.IBaseService;
import com.payment.IPaymentBehavior;
import com.translate.entity.Order;
import com.translate.entity.PayManager;
import com.translate.entity.User;
import com.translate.web.constant.OrderErrorMsg;
import com.translate.web.param.contract.IPayBehaviorRequestParam;
import com.translate.web.service.IChangeRecordService;
import com.translate.web.service.IOrderLogService;
import com.translate.web.service.IOrderService;
import com.translate.web.service.IPayManagerService;
import com.translate.web.service.IUserService;

public class RechargePayByOrder<T> implements IPaymentBehavior {

	private IBaseService<T>[] baseServices;
	
	public RechargePayByOrder(IBaseService<T>[] baseServices) {
		this.baseServices = baseServices;
	}
	
	/**
	 * 
	 * 用户端：		编辑端：			管理端：
	 * 	-1 待报价			待处理			待报价
	 * 	0  已报价			处理中			已报价
	 * 	1  待支付			已返稿			待支付
	 * 	2  待确认							待确认
	 * 	3  处理中							待派稿
	 * 	4  已返稿							处理中
	 * 	5  待审核
	 *  6  未通过
		7  已完成
		8  已取消							已返稿
	 * 									返回编辑确认
										待审核未通过
										已确认
										已完成
										已取消
	 * 
	 * 
	 */
	@Override
	public int pay(IPayBehaviorRequestParam behaviorRequestParam) {
		
		IOrderService orderService = (IOrderService) baseServices[0];
		
		Order payManager = orderService.getDataDetail(behaviorRequestParam);
		
		if (null == payManager) {
            return 3006;
        }
		
		if (0 == payManager.getServiceType()) { // 不是作图服务 不允许 在订单列表中支付
			return -6;
		}
		
		
		// 查询余额 够不够
		
		IUserService userService = (IUserService)baseServices[1];
		User userData = userService.selectByPrimaryKey((int) behaviorRequestParam.getUserId());
		
		BigDecimal academicCurrency = userData.getAcademicCurrency();
		
		BigDecimal priceSum = payManager.getServicePrice();
		if (-1 == academicCurrency.compareTo(priceSum)) {
			return OrderErrorMsg.INSUFFICIENT_BALANCE.getCode();
		}
		
		// 扣减余额
		academicCurrency.subtract(priceSum);
		
		User user = new User();
		
		user.setAcademicCurrency(academicCurrency.subtract(priceSum));
		
		user.setId(userData.getId());
		
		userService.update(userData);
		
		// 更新订单状态
		
		orderService.paySuccess(behaviorRequestParam);
		
		// 添加订单记录
		List<Order> ordersByUserIdAndManagerId = orderService.getOrdersByUserIdAndManagerId(behaviorRequestParam);
		
		IOrderLogService logService = (IOrderLogService) baseServices[3];
		
		logService.paySuccessOrderLog(behaviorRequestParam.getId(), (int)behaviorRequestParam.getUserId(), ordersByUserIdAndManagerId.stream().mapToInt(e->e.getId()).toArray());
		
		// 添加 余额 出账 记录
		IChangeRecordService recordService = (IChangeRecordService) baseServices[4];
		
        return recordService.addChangeRecord(behaviorRequestParam, priceSum);
	}
}
